import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import { Button, Modal } from 'antd';
import { useRef } from 'react';
import { deleteCategory, listManagement } from '@/services/mall/api';

export default () => {
  const actionRef = useRef<ActionType>(null);
  const navigate = useNavigate();

  const refreshTable = () => {
    actionRef.current?.reload();
  };

  const handleOpenForm = () => {
    // 跳转到新增页面
    navigate('add');
  };

  const handleRowEdit = (record: ProductType.ManagementList) => {
    // 跳转到编辑页面，将id作为参数携带
    navigate(`edit/${record.id}`);
  };

  const handleRowDel = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条记录吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await deleteCategory(id);
        refreshTable();
      },
    });
  };

  const columns: ProColumns<ProductType.ManagementList>[] = [
    { title: '图片', dataIndex: 'productImages', valueType: 'image' },
    { title: '编号/条码', dataIndex: 'productBarcode' },
    { title: '名称', dataIndex: 'productName' },
    { title: '商品分类', dataIndex: 'productType' },
    { title: '库存', dataIndex: 'stockQuantity' },
    { title: '价格', dataIndex: 'price' },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: { text: '正常' },
        1: { text: '停用', status: 'Default' },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_text, record) => [
        <a key="edit" onClick={() => handleRowEdit(record)}>
          编辑
        </a>,
        <a
          key="delete"
          style={{ color: '#f56c6c' }}
          onClick={() => {
            if (record.id != null) {
              handleRowDel(record.id);
            }
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  return (
    <ProTable<ProductType.ManagementList>
      actionRef={actionRef}
      request={async (_params, _sort, _filter) => {
        const msg = await listManagement();
        return {
          data: msg.list,
          success: true,
        };
      }}
      rowKey="id"
      pagination={{
        showQuickJumper: true,
      }}
      columns={columns}
      search={{ labelWidth: 'auto' }}
      dateFormatter="string"
      headerTitle="分类管理"
      toolBarRender={() => [
        <Button
          type="primary"
          key="button"
          icon={<PlusOutlined />}
          onClick={handleOpenForm}
        >
          添加
        </Button>,
      ]}
    />
  );
};
